<template>
    <div class="login_container">
        <div class="login_box">
            <!-- 左侧装饰区域 -->
            <div class="login_left">
                <h2 class="welcome_text">欢迎使用</h2>
                <h1 class="system_name">荷叶管理系统</h1>
                <p class="system_desc">专业的医疗管理平台</p>
            </div>
            
            <!-- 右侧登录表单 -->
            <div class="login_form">
                <div class="form_header">
                    <h3 class="title">账号登录</h3>
                    <p class="subtitle">请输入您的账号和密码</p>
                </div>
                
                <el-form ref="formRef" :model="loginForm" :rules="rules" class="form_content">
                    <!-- 用户名输入框 -->
                    <el-form-item prop="userName">
                        <el-input 
                            v-model="loginForm.userName" 
                            placeholder="请输入账号" 
                            :prefix-icon="User"
                            clearable
                        />
                    </el-form-item>
                    
                    <!-- 密码输入框 -->
                    <el-form-item prop="password">
                        <el-input 
                            v-model="loginForm.password" 
                            type="password" 
                            placeholder="请输入密码" 
                            :prefix-icon="Lock"
                            show-password 
                            clearable
                        />
                    </el-form-item>
                    
                    <!-- 验证码 -->
                    <el-form-item prop="captcha">
                        <div class="captcha_container">
                            <el-input 
                                v-model="loginForm.captcha" 
                                placeholder="请输入验证码"
                                :prefix-icon="Picture"
                                clearable 
                                :disabled="!captchaSrc"
                            />
                            <div class="captcha_box" @click="refreshCaptcha">
                                <img 
                                    v-if="captchaSrc" 
                                    :src="captchaSrc" 
                                    @error="handleCaptchaError"
                                    alt="验证码" 
                                    title="点击刷新验证码" 
                                />
                                <el-icon v-else><Refresh /></el-icon>
                            </div>
                        </div>
                    </el-form-item>

                    <!-- 登录按钮 -->
                    <el-form-item>
                        <el-button 
                            type="primary" 
                            class="login_button"
                            @click="handleLogin" 
                            :loading="loading"
                        >
                            {{ loading ? '登录中...' : '登录' }}
                        </el-button>
                    </el-form-item>

                    <!-- 其他登录方式 -->
                    <div class="other_login">
                        <el-divider>其他登录方式</el-divider>
                        <div class="login_icons">
                            <el-tooltip content="微信登录" placement="top">
                                <el-icon><ChromeFilled /></el-icon>
                            </el-tooltip>
                            <el-tooltip content="支付宝登录" placement="top">
                                <el-icon><ElemeFilled /></el-icon>
                            </el-tooltip>
                            <el-tooltip content="手机登录" placement="top">
                                <el-icon><Iphone /></el-icon>
                            </el-tooltip>
                        </div>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { Login, GetValidateCode } from "../api/user/index.js";
import { useRouter } from "vue-router";
import { userUserStore } from '../store/userStore.js';
import { ElMessage } from "element-plus";
import { User, Lock, Picture, Iphone } from '@element-plus/icons-vue';

const userStore = userUserStore();
const router = useRouter();
const formRef = ref(null);
const loading = ref(false);

const loginForm = ref({
    userName: 'user1',
    password: '123456',
    captcha: '',
    codeKey: ''
});

const rules = ref({
    userName: [
        { required: true, message: '用户名不可为空', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码不可为空', trigger: 'blur' },
        { min: 6, max: 12, message: '密码长度在6~12之间', trigger: 'blur' },
    ],
    captcha: [
        { required: true, message: '验证码不可为空', trigger: 'blur' },
    ]
});

const captchaSrc = ref('');

const maxRetries = 3; // 最大重试次数
const retryDelay = 1000; // 重试延迟(毫秒)

// 带重试机制的验证码刷新
async function refreshCaptcha(retryCount = 0) {
    try {
        const res = await GetValidateCode();
        console.log('验证码响应:', res); // 添加日志查看响应结构
        
        // 直接使用 res 而不是 res.data
        if (res && res.code === 200 && res.data) {
            loginForm.value.codeKey = res.data.codeKey;
            captchaSrc.value = res.data.codeValue;
        } else {
            console.error('验证码数据格式错误:', res);
            throw new Error('验证码获取失败');
        }
    } catch (error) {
        console.error('获取验证码失败:', error);

        if (retryCount < maxRetries) {
            ElMessage.warning(`验证码获取失败，${retryCount + 1}秒后重试...`);
            await new Promise(resolve => setTimeout(resolve, retryDelay));
            return refreshCaptcha(retryCount + 1);
        } else {
            ElMessage.error('验证码服务暂时不可用，请稍后再试');
            captchaSrc.value = ''; // 清空验证码图片
        }
    }
}

// 登录处理
async function handleLogin() {
    if (!captchaSrc.value) {
        ElMessage.warning('请等待验证码加载完成');
        return;
    }

    try {
        const valid = await formRef.value.validate();
        if (valid) {
            loading.value = true;
            const loginData = {
                userName: loginForm.value.userName,
                password: loginForm.value.password,
                captcha: loginForm.value.captcha,
                codeKey: loginForm.value.codeKey
            };
            
            console.log('登录请求数据:', loginData);
            
            const res = await Login(loginData);
            console.log('登录响应数据:', res);

            // 直接使用 res 而不是 res.data
            if (res && res.code === 200) {
                if (res.data && res.data.token) {
                    localStorage.setItem("token", res.data.token);
                    localStorage.setItem("user", JSON.stringify(res.data.user));
                    ElMessage.success("登录成功");
                    router.push('/index');
                } else {
                    throw new Error('登录响应缺少必要数据');
                }
            } else {
                const errorMsg = res?.msg || '登录失败';
                ElMessage.error(errorMsg);
                console.error('登录失败:', errorMsg);
                await refreshCaptcha(); // 刷新验证码
                loginForm.value.captcha = ''; // 清空验证码输入
            }
        }
    } catch (error) {
        console.error('登录请求出错:', error);
        ElMessage.error(error.message || '登录失败，请检查网络连接');
        await refreshCaptcha();
        loginForm.value.captcha = ''; // 清空验证码输入
    } finally {
        loading.value = false;
    }
}

// 验证码图片加载失败处理
function handleCaptchaError() {
    refreshCaptcha();
}

// 组件挂载时获取初始验证码
onMounted(() => {
    refreshCaptcha();
});
</script>

<style lang="scss" scoped>
.login_container {
    min-height: 100vh;
    background: linear-gradient(135deg, #e0f2f1 0%, #80cbc4 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;

    .login_box {
        width: 1000px;
        height: 600px;
        background: #fff;
        border-radius: 20px;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
        display: flex;
        overflow: hidden;
        animation: fadeIn 0.5s ease;

        .login_left {
            flex: 1;
            background: linear-gradient(135deg, #26a69a 0%, #00897b 100%);
            padding: 60px 40px;
            color: white;
            display: flex;
            flex-direction: column;
            justify-content: center;

            .welcome_text {
                font-size: 28px;
                margin-bottom: 20px;
                opacity: 0;
                animation: slideUp 0.5s ease forwards 0.2s;
            }

            .system_name {
                font-size: 36px;
                font-weight: bold;
                margin-bottom: 20px;
                opacity: 0;
                animation: slideUp 0.5s ease forwards 0.4s;
            }

            .system_desc {
                font-size: 16px;
                opacity: 0.9;
                opacity: 0;
                animation: slideUp 0.5s ease forwards 0.6s;
            }
        }

        .login_form {
            flex: 1;
            padding: 40px;
            display: flex;
            flex-direction: column;

            .form_header {
                text-align: center;
                margin-bottom: 40px;

                .title {
                    font-size: 24px;
                    color: #333;
                    margin-bottom: 10px;
                }

                .subtitle {
                    color: #999;
                    font-size: 14px;
                }
            }

            .form_content {
                width: 100%;
                max-width: 360px;
                margin: 0 auto;

                .el-input {
                    --el-input-hover-border-color: #26a69a;
                    --el-input-focus-border-color: #26a69a;
                }

                .captcha_container {
                    display: flex;
                    gap: 12px;

                    .el-input {
                        flex: 1;
                    }

                    .captcha_box {
                        width: 120px;
                        height: 40px;
                        border-radius: 4px;
                        overflow: hidden;
                        cursor: pointer;
                        transition: all 0.3s;

                        &:hover {
                            opacity: 0.8;
                        }

                        img {
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                        }

                        .el-icon {
                            width: 100%;
                            height: 100%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            background: #f5f7fa;
                            font-size: 20px;
                            color: #909399;
                        }
                    }
                }

                .login_button {
                    width: 100%;
                    height: 44px;
                    margin-top: 20px;
                    background: linear-gradient(135deg, #26a69a 0%, #00897b 100%);
                    border: none;
                    font-size: 16px;
                    transition: all 0.3s;

                    &:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 4px 12px rgba(38, 166, 154, 0.3);
                    }
                }

                .other_login {
                    margin-top: 30px;

                    .el-divider {
                        --el-border-color: #e0e0e0;
                        color: #999;
                    }

                    .login_icons {
                        display: flex;
                        justify-content: center;
                        gap: 40px;
                        margin-top: 20px;

                        .el-icon {
                            font-size: 24px;
                            color: #666;
                            cursor: pointer;
                            transition: all 0.3s;

                            &:hover {
                                color: #26a69a;
                                transform: translateY(-2px);
                            }
                        }
                    }
                }
            }
        }
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>